package net.lastcoder.ytl;

import net.lastcoder.ifserver.Globals;
import net.lastcoder.ifserver.Server;
import net.lastcoder.ifserver.cache.ExpireStrategy;
import net.lastcoder.ifserver.nio.UnauthorizedException;
import net.lastcoder.ifserver.packet.Event;
import net.lastcoder.ifserver.packet.EventHandler;
import net.lastcoder.ifserver.route.EventHandlerManager;
import net.lastcoder.ifserver.session.Session;
import net.lastcoder.ifserver.session.SessionListener;
import net.lastcoder.ifserver.session.SessionManager;
import net.lastcoder.ifserver.util.Md5;
import net.lastcoder.ifserver.web.WebManager;
import net.lastcoder.ifserver.plugin.Plugin;
import net.lastcoder.ifserver.plugin.PluginManager;
import net.lastcoder.ifserver.util.TextUtils;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**一个简单的聊天服务端，
 * 热更新可以通过tools中的例子快速更新
 * auth: WenYF
 * date: 2017/2/6
 */
public class YtlPlugin implements Plugin {
    private static final Logger Log = LoggerFactory.getLogger(YtlPlugin.class);
    private ConcurrentHashMap<String, JSONObject> players = new ConcurrentHashMap<>();
    private EventHandler eventHandler = new EventHandler("ytl event handler", (short) 1000) {
        @Override
        public boolean handle(Session from, Event packet) throws UnauthorizedException {
            String username = from.getUsername();
            switch (packet.getActionCode()) {
                case 1:
                    // 客户端请求玩家列表
                    JSONArray jsonArray = new JSONArray();
                    for (JSONObject json : players.values()) {
                        jsonArray.put(json);
                    }
                    JSONObject userJson = new JSONObject();
                    try {
                        userJson.put("users", jsonArray);
                        packet = packet.createResult();
                        packet.setActionCode(2);
                        packet.setBody(userJson.toString());
                        broadcast(packet);
                    } catch (Exception e) {
                        Log.error(e.getMessage(), e);
                    }
                    break;
//                case 2:
//                    // 得到玩家列表
//                    break;
//                case 3:
//                    // 发送数据到客户端
//                    break;
                case 4:
                    // 收到客户端发来的数据
                    try {
                        JSONObject playerJson = players.get(username);
                        if (playerJson == null) {
                            return false;
                        }

                        JSONObject json = new JSONObject();
                        json.put("uid", username);
                        json.put("text", packet.getBody());

                        packet = packet.createResult();
                        packet.setBody(json.toString());
                        packet.setActionCode(3);
                        broadcast(packet);
                    } catch (JSONException e) {
                        Log.error(e.getMessage(), e);
                    }

                    break;
            }
            return true;
        }

        @Override
        public void reload() {
        }
    };

    private void broadcast(Event event) {
        for (Session session : SessionManager.getInstance().getSessions()) {
            session.process(event);
        }
    }

    private SessionListener sessionListener = new SessionListener() {
        @Override
        public void sessionCreated(Session session) {

        }

        @Override
        public void sessionAuthenticated(Session session) {
            // 建立连接
            JSONObject json = players.get(session.getUsername());
            if (json == null) {
                json = new JSONObject();
                try {
                    json.put("uid", session.getUsername());
                    json.putOpt("name", session.getAttribute("token"));
                    players.put(session.getUsername(), json);
                } catch (JSONException e) {
                    Log.error(e.getMessage(), e);
                }
            }
        }

        @Override
        public void sessionDestroy(Session session) {

        }
    };

    @Override
    public void initializePlugin(PluginManager manager, File pluginDirectory) {
        SessionManager.getInstance().addSessionListener(sessionListener);
        EventHandlerManager.getInstance().putEventHandler(eventHandler);
        System.out.println("init ytl plugin success.");
        Log.debug("init ytl plugin success.");
    }

    @Override
    public void destroyPlugin() {
        EventHandlerManager.getInstance().removeEventHandler(eventHandler);
        SessionManager.getInstance().removeSessionListener(sessionListener);
    }

}
